package com.sinoatma.physignsmonitor.fragment

import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.common.frame.base.BaseViewModel
import com.common.frame.base.toJson
import com.google.gson.Gson
import com.sinoatma.physignsmonitor.MyApp
import com.sinoatma.physignsmonitor.MyApp.Companion.monitorRecordDao
import com.sinoatma.physignsmonitor.bean.BloodCollectListBean
import com.sinoatma.physignsmonitor.bean.MonitorRecordEntity
import com.sinoatma.physignsmonitor.constant.devicesNumber
import com.sinoatma.physignsmonitor.http.NetManager
import com.sinoatma.physignsmonitor.utils.FileUtils.getFileFromPath
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import java.util.*
import kotlin.collections.HashMap

/**
 * @ProjectName : PhySignsMonitor
 * @Author :
 * @Time : 2024/12/30 15:41
 * @Description : 文件描述
 */
class HistoryListViewModel:BaseViewModel() {

    var dataList : MutableLiveData<List<BloodCollectListBean>> = MutableLiveData()

    var dataMsg : MutableLiveData<String> = MutableLiveData()

    var filePath:String=""

    // 分页加载数据
    fun getRecordsByPage(page: Int, pageSize: Int): LiveData<List<MonitorRecordEntity>> {
        val offset = page * pageSize
        val recordsLiveData = MutableLiveData<List<MonitorRecordEntity>>()
        viewModelScope.launch(Dispatchers.IO) {
            val records = monitorRecordDao.getRecordsByPage(pageSize, offset)
            recordsLiveData.postValue(records)
        }

        return recordsLiveData
    }

    fun  initExcelFolder(){
        val dir = File(MyApp.context.getExternalFilesDir(null), "sinoatma/Excel")
        if (!dir.exists()) {
            dir.mkdirs()
        }
        filePath="${dir}/temp.xlsx"
    }

    fun bloodCollectList(page: Int){
        Log.e("zsy","page=${page}")
        val jsonMap = HashMap<String, Any>()
        jsonMap["pageNum"]=page
        jsonMap["pageSize"]=30
        jsonMap["status"]=0
        jsonMap["deviceNumber"]= devicesNumber
        val gson = Gson()
        val toJson = gson.toJson(jsonMap)
        launchRequest({NetManager.bloodCollectList( RequestBody.create("application/json;charset=UTF-8".toMediaTypeOrNull(), toJson))},{
            dataList.value=it
        },{
            dataMsg.value="${it.code}  ${it.message}  ${it.msg}"
        })
    }


    


}